import {useUserStore} from '@/stores/modules/user.store'
import {useWebConfigStore} from '@/stores/modules/webConfig.store'
import {Local} from '@/utils/storageUtil'
import {cacheKeys} from '@/stores/constant/cacheKey'

const watermarkId = 'watermark_' + new Date().getTime()

const setWatermark = (str?: string): string | undefined => {
	if (!str) {
		return undefined
	}
	// 清除旧水印
	if (document.getElementById(watermarkId) !== null) {
		document.body.removeChild(document.getElementById(watermarkId)!)
	}
	// 创建一个画布
	const can = document.createElement('canvas')
	// 设置画布的长宽
	can.width = 400
	can.height = 400
	const cans = can.getContext('2d')
	// 旋转角度
	cans?.rotate(-35 * Math.PI / 180)
	cans!.font = '15px Vedana'
	// 设置填充绘画的颜色、渐变或者模式
	const webConfigStore = useWebConfigStore()
	cans!.fillStyle = webConfigStore.layout.isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.15)'
	// 设置文本内容的当前对齐方式
	cans!.textAlign = 'left'
	// 设置在绘制文本时使用的当前文本基线
	cans!.textBaseline = 'middle'
	// 在画布上绘制填色的文本（输出的文本，开始绘制文本的X坐标位置，开始绘制文本的Y坐标位置）
	cans?.fillText(str, can.width / 10, can.height / 2)
	const div = document.createElement('div')
	div.id = watermarkId
	div.style.pointerEvents = 'none'
	div.style.top = '30px'
	div.style.left = '0px'
	div.style.position = 'fixed'
	div.style.zIndex = '100000'
	div.style.width = document.documentElement.clientWidth + 'px'
	div.style.height = document.documentElement.clientHeight + 'px'
	div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
	document.body.appendChild(div)
	return watermarkId
}

const removeWatermark = () => {
	if (document.getElementById(watermarkId) !== null) {
		document.body.removeChild(document.getElementById(watermarkId)!)
	}
}

const generateDefaultMark = (): string | undefined => {
	const userStore = useUserStore()
	if (Local.get(cacheKeys.TOKEN)) {
		let watermarkStr = ''
		if (userStore.nickname) {
			watermarkStr += userStore.nickname
		}
		if (userStore.username) {
			watermarkStr += ('-' + userStore.username)
		}
		if (watermarkStr) {
			return watermarkStr
		} else {
			return undefined
		}
	} else {
		return undefined
	}
}

const watermarkUtil = {
	set: (str?: string): string | undefined => {
		return setWatermark(str || generateDefaultMark())
	},
	remove: () => {
		removeWatermark()
	},
	watermarkId: watermarkId
}

export default watermarkUtil
